package com.boilermaker.lotterysystem.service.impl;

import com.boilermaker.lotterysystem.controller.param.PageParam;
import com.boilermaker.lotterysystem.controller.param.PrizeParam;
import com.boilermaker.lotterysystem.dao.dataobject.PrizeDO;
import com.boilermaker.lotterysystem.dao.mapper.PrizeMapper;
import com.boilermaker.lotterysystem.service.PictureService;
import com.boilermaker.lotterysystem.service.PrizeService;
import com.boilermaker.lotterysystem.service.dto.PageListDTO;
import com.boilermaker.lotterysystem.service.dto.PrizeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 奖品服务模块
 */
@Service
public class PrizeServiceImpl implements PrizeService {

    /**
     * 注入图片服务
     */
    @Autowired
    private PictureService pictureService;

    /**
     * 注入数据访问
     */
    @Autowired
    private PrizeMapper prizeMapper;

    /**
     * 创建奖品
     *
     * @param param   奖品属性
     * @param picture 奖品图
     * @return 奖品 ID
     */
    @Override
    public Long createPrize(PrizeParam param, MultipartFile picture) {

        String fileName = pictureService.savePicture(picture);

        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setPrice(param.getPrice());
        prizeDO.setImageUrl(fileName);

        prizeMapper.insert(prizeDO);

        return prizeDO.getId();
    }

    /**
     * 获取奖品列表，支持翻页功能
     *
     * @param param
     * @return
     */
    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageParam param) {

        List<PrizeDO> prizeDOList = prizeMapper.findPrizeListByPage(
                param.offset(), param.getPageSize());

        PageListDTO<PrizeDTO> pageListDTO = new PageListDTO<>();

        pageListDTO.setTotal(prizeMapper.count());
        pageListDTO.setRecords( // 将 List<PrizeDO> 映射为 List<PrizeDTO>
                prizeDOList.stream().map(prizeDO -> {

                    PrizeDTO dto = new PrizeDTO();
                    dto.setPrizeId(prizeDO.getId());
                    dto.setPrizeName(prizeDO.getName());
                    dto.setDescription(prizeDO.getDescription());
                    dto.setImageUrl(prizeDO.getImageUrl());
                    dto.setPrice(prizeDO.getPrice());

                    return dto;
                }).collect(Collectors.toList())
        );

        return pageListDTO;
    }
}
